package com.question.mapper;

//wjb
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.question.pojo.dto.QuestionPageDTO;
import com.question.pojo.dto.UserQuestionDTO;
import com.question.pojo.entity.Question;
import com.question.pojo.entity.Blank;
import com.question.pojo.entity.Choice;
import com.question.pojo.vo.QuestionPageVO;
import com.question.pojo.vo.QuestionVO;
import com.question.pojo.vo.UserQuestionVO;
import org.apache.ibatis.annotations.*;

//ycl
//import com.baomidou.mybatisplus.core.mapper.BaseMapper;
//import com.question.pojo.dto.QuestionDTO;
//import com.question.pojo.dto.QuestionPageDTO;
//import com.question.pojo.dto.QuestionPageDTO;
//import com.question.pojo.entity.Question;
//import com.question.pojo.vo.QuestionPageVO;
//import com.question.pojo.vo.QuestionVO;
//import com.question.pojo.vo.QuestionVO;
//import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.Map;

//@Mapper
//public interface QuestionMapper extends BaseMapper<Question> {
//
//    List<QuestionPageVO> listPage(QuestionPageDTO questionPageDTO);
//
//    List<QuestionVO> listAllQuestions(QuestionDTO questionDTO);
//
//}

@Mapper
public interface QuestionMapper extends BaseMapper<Question> {

    List<QuestionPageVO> listPage(QuestionPageDTO questionPageDTO);

    List<UserQuestionVO> listAllQuestions(UserQuestionDTO questionDTO);

//    /**
//     * 获取题目列表（分页）
//     * @param params 查询参数
//     * @return 题目列表
//     */
//    @Select({
//            "<script>",
//            "SELECT q.question_id, q.question_type, q.content, q.answer, q.max_length,",
//            "q.base_score, q.weight, q.created_at, q.created_by, q.category_id,",
//            "c.category_name, u.username AS creator,",
//            "m.major_id, m.major_name",
//            "FROM questions q",
//            "JOIN question_categories c ON q.category_id = c.category_id",
//            "JOIN majors m ON c.major_id = m.major_id",
//            "JOIN user u ON q.created_by = u.user_id",
//            "<where>",
//            "   <if test='params.questionType != null and params.questionType != \"\"'>",
//            "       AND q.question_type = #{params.questionType}",
//            "   </if>",
//            "   <if test='params.categoryId != null'>",
//            "       AND q.category_id = #{params.categoryId}",
//            "   </if>",
//            "   <if test='params.majorId != null'>",
//            "       AND c.major_id = #{params.majorId}",
//            "   </if>",
//            "   <if test='params.keyword != null and params.keyword != \"\"'>",
//            "       AND (q.content LIKE CONCAT('%', #{params.keyword}, '%')",
//            "       OR q.answer LIKE CONCAT('%', #{params.keyword}, '%')",
//            "       OR c.category_name LIKE CONCAT('%', #{params.keyword}, '%')",
//            "       OR m.major_name LIKE CONCAT('%', #{params.keyword}, '%'))",
//            "   </if>",
//            "</where>",
//            "ORDER BY q.created_at DESC",
//            "</script>"
//    })
//    List<QuestionVO> selectQuestionList(@Param("params") Map<String, Object> params);

    /**
     * 获取题目列表（分页）
     * @param questionType
     * @param keyword
     * @param majorId
     * @param categoryId
     * @param offset
     * @param pageSize
     * @return
     */
    @Select("<script>" +
            "SELECT q.question_id, q.question_type, q.content, q.answer, q.max_length, " +
            "q.base_score, q.weight, q.created_at, q.created_by, q.category_id, " +
            "c.category_name, u.username AS creator, " +
            "m.major_id, m.major_name " +
            "FROM questions q " +
            "JOIN question_categories c ON q.category_id = c.category_id " +
            "JOIN majors m ON c.major_id = m.major_id " +
            "JOIN user u ON q.created_by = u.user_id " +
            "<where>" +
            "   <if test='questionType != null and questionType != \"\"'>" +
            "       AND q.question_type = #{questionType}" +
            "   </if>" +
            "   <if test='categoryId != null'>" +
            "       AND q.category_id = #{categoryId}" +
            "   </if>" +
            "   <if test='majorId != null'>" +
            "       AND c.major_id = #{majorId}" +
            "   </if>" +
            "   <if test='keyword != null and keyword != \"\"'>" +
            "       AND (q.content LIKE CONCAT('%', #{keyword}, '%') " +
            "       OR q.answer LIKE CONCAT('%', #{keyword}, '%') " +
            "       OR c.category_name LIKE CONCAT('%', #{keyword}, '%') " +
            "       OR m.major_name LIKE CONCAT('%', #{keyword}, '%')" +
            "   </if>" +
            "</where>" +
            "ORDER BY q.created_at DESC " +
            "LIMIT #{offset}, #{pageSize}" +
            "</script>")
    List<QuestionVO> selectQuestionList(
            @Param("questionType") String questionType,
            @Param("keyword") String keyword,
            @Param("majorId") Integer majorId,
            @Param("categoryId") Integer categoryId,
            @Param("offset") Integer offset,
            @Param("pageSize") Integer pageSize);

    @Select("<script>" +
            "SELECT COUNT(*) " +
            "FROM questions q " +
            "JOIN question_categories c ON q.category_id = c.category_id " +
            "JOIN majors m ON c.major_id = m.major_id " +
            "JOIN user u ON q.created_by = u.user_id " +
            "<where>" +
            "   <if test='questionType != null and questionType != \"\"'>" +
            "       AND q.question_type = #{questionType}" +
            "   </if>" +
            "   <if test='categoryId != null'>" +
            "       AND q.category_id = #{categoryId}" +
            "   </if>" +
            "   <if test='majorId != null'>" +
            "       AND c.major_id = #{majorId}" +
            "   </if>" +
            "   <if test='keyword != null and keyword != \"\"'>" +
            "       AND (q.content LIKE CONCAT('%', #{keyword}, '%') " +
            "       OR q.answer LIKE CONCAT('%', #{keyword}, '%') " +
            "       OR c.category_name LIKE CONCAT('%', #{keyword}, '%') " +
            "       OR m.major_name LIKE CONCAT('%', #{keyword}, '%')" +
            "   </if>" +
            "</where>" +
            "</script>")
    int countQuestionList(
            @Param("questionType") String questionType,
            @Param("keyword") String keyword,
            @Param("majorId") Integer majorId,
            @Param("categoryId") Integer categoryId);

    /**
     * 根据ID获取题目详情
     * @param questionId 题目ID
     * @return 题目详情
     */
    @Select({
            "SELECT q.question_id, q.question_type, q.content,",
            "q.base_score, q.weight, q.created_at, q.created_by, q.category_id,",
            "c.category_name, u.username AS creator,",
            "m.major_id, m.major_name,",
            "IFNULL(s.total_attempts, 0) AS total_attempts,", // 总答题次数
            "IFNULL(s.correct_attempts, 0) AS correct_attempts,", // 正确次数
            "IFNULL(ROUND(s.correct_attempts * 100.0 / NULLIF(s.total_attempts, 0), 0), 0) AS correct_rate,", // 正确率
            "(SELECT COUNT(*) FROM user_favorites f WHERE f.question_id = q.question_id) AS favorite_count", // 收藏人数
            "FROM questions q",
            "LEFT JOIN question_categories c ON q.category_id = c.category_id",
            "LEFT JOIN majors m ON c.major_id = m.major_id",
            "LEFT JOIN user u ON q.created_by = u.user_id",
            "LEFT JOIN question_statistics s ON q.question_id = s.question_id",
            "WHERE q.question_id = #{questionId}"
    })
    @Results({
            @Result(property = "questionId", column = "question_id"), // 添加基础字段映射
            @Result(property = "choices", column = "question_id",
                    many = @Many(select = "selectChoicesByQuestionId")),
            @Result(property = "blanks", column = "question_id",
                    many = @Many(select = "selectBlanksByQuestionId"))
    })
    QuestionVO getQuestionById(Integer questionId);

    /**
     * 获取题目的选择题选项
     * @param questionId 题目ID
     * @return 选择题选项列表
     */
    @Select("SELECT * FROM question_choices WHERE question_id = #{questionId} ORDER BY choice_id")
    List<Choice> selectChoicesByQuestionId(Integer questionId);

    /**
     * 获取题目的填空题空位
     * @param questionId 题目ID
     * @return 填空题空位列表
     */
    @Select("SELECT * FROM question_blanks WHERE question_id = #{questionId} ORDER BY blank_index")
    List<Blank> selectBlanksByQuestionId(Integer questionId);



    /**
     * 添加新题目
     * @param question 题目实体
     */
    @Insert({
            "INSERT INTO questions (question_type, content, answer, max_length, ",
            "base_score, weight, created_by, category_id, major_id)", // 添加 major_id 字段
            "VALUES (#{questionType}, #{content}, #{answer}, #{maxLength}, ",
            "#{baseScore}, #{weight}, #{createdBy}, #{categoryId}, ",
            "(SELECT major_id FROM question_categories WHERE category_id = #{categoryId}))" // 通过子查询获取 major_id
    })
    @Options(useGeneratedKeys = true, keyProperty = "questionId")
    void insertQuestion(Question question);

    /**
     * 批量插入选择题选项
     * @param choices 选项列表
     */
    @Insert({
            "<script>",
            "INSERT INTO question_choices (question_id, choice_content, is_correct)",
            "VALUES ",
            "<foreach collection='list' item='choice' separator=','>",
            "(#{choice.questionId}, #{choice.choiceContent}, #{choice.isCorrect})",
            "</foreach>",
            "</script>"
    })
    void insertChoicesBatch(@Param("list") List<Choice> choices); // 添加 @Param 注解

    /**
     * 批量插入填空题空位
     * @param blanks 空位列表
     */
    @Insert({
            "<script>",
            "INSERT INTO question_blanks (question_id, blank_index, answer, max_length)",
            "VALUES ",
            "<foreach collection='blanks' item='blank' separator=','>",
            "(#{blank.questionId}, #{blank.blankIndex}, #{blank.answer}, #{blank.maxLength})",
            "</foreach>",
            "</script>"
    })
    void insertBlanksBatch(@Param("blanks") List<Blank> blanks); // 添加 @Param 注解



    /**
     * 编辑更新题目
     * @param question 题目实体
     * @return 更新的行数
     */
    @Update({
            "UPDATE questions SET",
            "question_type = #{questionType}, ",
            "content = #{content}, ",
            "answer = #{answer}, ",
            "base_score = #{baseScore}, ",
            "weight = #{weight}, ",
            "category_id = #{categoryId}, ",
            "major_id = (SELECT major_id FROM question_categories WHERE category_id = #{categoryId}) ", // 添加major_id更新
            "WHERE question_id = #{questionId}"
    })
    int updateQuestion(Question question);

    /**
     * 批量更新选择题选项 (使用CASE WHEN优化)
     */
    @Update({
            "<script>",
            "UPDATE question_choices",
            "SET choice_content = CASE",
            "  <foreach collection='list' item='item'>",
            "    WHEN choice_id = #{item.choiceId} THEN #{item.choiceContent}",
            "  </foreach>",
            "END,",
            "is_correct = CASE",
            "  <foreach collection='list' item='item'>",
            "    WHEN choice_id = #{item.choiceId} THEN #{item.isCorrect}",
            "  </foreach>",
            "END",
            "WHERE choice_id IN",
            "  <foreach collection='list' item='item' open='(' separator=',' close=')'>",
            "    #{item.choiceId}",
            "  </foreach>",
            "</script>"
    })
    void updateChoicesBatch(List<Choice> choices);

    /**
     * 批量更新填空题空位 (使用CASE WHEN优化)
     */
    @Update({
            "<script>",
            "UPDATE question_blanks",
            "SET answer = CASE",
            "  <foreach collection='list' item='item'>",
            "    WHEN blank_id = #{item.blankId} THEN #{item.answer}",
            "  </foreach>",
            "END,",
            "max_length = CASE",
            "  <foreach collection='list' item='item'>",
            "    WHEN blank_id = #{item.blankId} THEN #{item.maxLength}",
            "  </foreach>",
            "END",
            "WHERE blank_id IN",
            "  <foreach collection='list' item='item' open='(' separator=',' close=')'>",
            "    #{item.blankId}",
            "  </foreach>",
            "</script>"
    })
    void updateBlanksBatch(List<Blank> blanks);



    /**
     * 删除题目的选择题选项
     * @param questionId 题目ID
     */
    @Delete("DELETE FROM question_choices WHERE question_id = #{questionId}")
    void deleteChoicesByQuestionId(Integer questionId);

    /**
     * 删除题目的填空题空位
     * @param questionId 题目ID
     */
    @Delete("DELETE FROM question_blanks WHERE question_id = #{questionId}")
    void deleteBlanksByQuestionId(Integer questionId);

    /**
     * 删除题目
     * @param questionId 题目ID
     */
    @Delete("DELETE FROM questions WHERE question_id = #{questionId}")
    void deleteQuestion(Integer questionId);

    /**
     * 批量删除选项
     */
    @Delete({
            "<script>",
            "DELETE FROM question_choices WHERE choice_id IN",
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    void deleteChoicesByIds(@Param("ids") List<Integer> ids); // 添加@Param注解

    /**
     * 批量删除空位
     */
    @Delete({
            "<script>",
            "DELETE FROM question_blanks WHERE blank_id IN",
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    void deleteBlanksByIds(@Param("ids") List<Integer> ids); // 添加@Param注解

    @Select("select * from questions where question_id = #{questionId}")
    Question selectByQuestionId(Integer questionId);


    @Select("SELECT COUNT(*) FROM questions WHERE category_id = #{categoryId}")
    int countQuestionsByCategory(Integer categoryId);

}
